package Util.Impl;
import Util.Token;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

public class TokenImpl implements Token {
    public String createToken(String username){
        String header="{\"typ\":\"JWT\",\"alg\",\"HS256\"}";
        header=Base64.getEncoder().encodeToString(header.getBytes());

        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
        String payload="{\"sub\":\""+username+"\",\"iat\":\""+format.format(new Date(new Date().getTime()+1000*60*60*24))+"\"}";
        payload=Base64.getEncoder().encodeToString(payload.getBytes());

        MessageDigest messageDigest;
        String encodeStr = header+"."+payload+".6w8+2k3k%wv(&ek)3g7v!7llqr!v4r$!lcevka3cahl64^&%lo";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(encodeStr.getBytes());
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        //System.out.println(encodeStr);
        System.out.println("发放token：  "+header+"."+payload+"."+encodeStr);
        //System.out.println(header);
        //System.out.println(new String(Base64.getDecoder().decode(header)));
        //System.out.println(payload);
        return header+"."+payload+"."+encodeStr;
    }
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
    // 验证token
    public String verify(String token){
        String header,payload,signature;
        try {
            String[] x = token.split("\\.");
            header = x[0];
            payload = x[1];
            signature = x[2];
        }
        catch (Exception e){
            System.out.println("token:"+token+",异常,token格式错误,分割长度异常");
            return "";
        }
        MessageDigest messageDigest;
        String encodeStr = header+"."+payload+".6w8+2k3k%wv(&ek)3g7v!7llqr!v4r$!lcevka3cahl64^&%lo";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(encodeStr.getBytes());
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        if(encodeStr.equals(signature)){
            String iat=new String(Base64.getDecoder().decode(payload)).split("\\,")[1].split("\\\"")[3];
            //System.out.println(new String(Base64.getDecoder().decode(payload)));
            System.out.print("name:"+new String(Base64.getDecoder().decode(payload)).split("\\,")[0].split("\\\"")[3]);
            System.out.print(" --- iat:"+new String(Base64.getDecoder().decode(payload)).split("\\,")[1].split("\\\"")[3]);

            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
            String now=format.format(new Date());
            System.out.println(" --- now:"+now);
            if(now.compareTo(iat)<0)
                return new String(Base64.getDecoder().decode(payload)).split("\\,")[0].split("\\\"")[3];
            else
                return "";
        }
        else
            return "";
    }
}
